package dao

import (
	"datum_user/config"
	"fmt"
	"github.com/sirupsen/logrus"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
)

var Db *gorm.DB

func InitMysql() {
	db, err := createDatabase()
	if err != nil {
		logrus.WithError(err).Fatalln("create database connection failed")
	} else {
		Db = db
	}
}

func createDatabase() (*gorm.DB, error) {
	dbAddr := config.GetString("mysql.addr")
	dbName := config.GetString("mysql.database")
	dbUser := config.GetString("mysql.user")
	dbPassword := config.GetString("mysql.password")
	dbCharset := config.GetString("mysql.charset")
	conn := fmt.Sprintf("%s:%s@(%s)/%s?charset=%s&parseTime=True&loc=Local", dbUser, dbPassword, dbAddr, dbName, dbCharset)
	return gorm.Open(mysql.Open(conn), &gorm.Config{})
}
